#!/bin/zsh

DNSMASQ_EXECUTABLE=/usr/sbin/dnsmasq

ok () {
	echo "[ "${GREEN_START}"OK"${GREEN_STOP}" ]"
}

failed () {
	echo "[ "${RED_START}"FAILED"${RED_STOP}" ]"
}

install_dnsmasq () {
	echo -n "installing service dnsmasq: "
	/sbin/apk add --no-cache dnsmasq 2> /dev/null && ok || failed
}

status_dnsmasq () {
	echo -n "status of service dnsmasq: "
	PID_FILE=/run/dnsmasq.pid
	if [ -f ${PID_FILE} ]; then
		PID=`ps aux | grep ${DNSMASQ_EXECUTABLE} | sed '/grep/d' | sed 's/^\s\+\(\d\+\).*/\1/g'  `
		if [ ${PID} = `cat ${PID_FILE}` ]; then
			ok
			return 0
		fi
	fi
	failed
	return 1
}

start_dnsmasq () {
	if [ ! -f ${DNSMASQ_EXECUTABLE} ]; then
		install_dnsmasq
	fi
	echo -n "starting service dnsmasq: "
	status_dnsmasq > /dev/null
	if [ $? -eq 0 ]; then
		ok
	else
		${DNSMASQ_EXECUTABLE} -x ${PID_FILE} && ok || failed
	fi
}

main() {
	action=$1
	case $action in 
		install)
			install_dnsmasq
			;;
		start)
			start_dnsmasq
			;;
		status)
			status_dnsmasq
			;;
		*)
	esac
}

main $@
